<template>
  <div class="settings-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统设置</span>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="系统名称" prop="siteName">
          <el-input v-model="form.siteName" />
        </el-form-item>
        
        <el-form-item label="系统Logo" prop="logo">
          <el-upload
            class="logo-upload"
            action="/api/upload/logo"
            :show-file-list="false"
            :on-success="handleLogoSuccess"
            :on-error="handleLogoError"
            :before-upload="beforeLogoUpload"
            name="image"
            :headers="uploadHeaders"
          >
            <template v-if="form.logo">
              <img 
                :src="form.logo" 
                class="logo" 
                @error="handleLogoLoadError"
                ref="logoImgRef"
              >
            </template>
            <el-icon v-else class="upload-icon"><Plus /></el-icon>
          </el-upload>
          <div class="logo-tip">建议尺寸: 200x60px，大小不超过2MB</div>
        </el-form-item>
        
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        
        <el-form-item label="联系邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        
        <el-form-item label="备案信息" prop="icp">
          <el-input v-model="form.icp" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">保存设置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getConfig, updateConfig } from '@/api/settings'

const loading = ref(false)
const formRef = ref(null)
const logoImgRef = ref(null)

const form = ref({
  siteName: '',
  logo: '',
  phone: '',
  email: '',
  address: '',
  icp: ''
})

// 添加请求头，用于验证
const uploadHeaders = computed(() => {
  return { 
    Authorization: `Bearer ${localStorage.getItem('token') || ''}` 
  }
})

const rules = {
  siteName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 获取配置
const fetchConfig = async () => {
  loading.value = true
  try {
    const { data } = await getConfig()
    Object.assign(form.value, data)
    console.log('获取到的配置:', data)
  } catch (error) {
    ElMessage.error('获取配置失败')
    console.error('获取配置失败:', error)
  } finally {
    loading.value = false
  }
}

// Logo图片加载错误
const handleLogoLoadError = (e) => {
  console.error('Logo图片加载失败:', e)
  
  // 尝试使用备用路径
  const img = e.target
  const originalSrc = img.src
  
  console.log('原始图片路径:', originalSrc)
  
  // 尝试多种路径格式
  setTimeout(() => {
    if (form.value.logo && form.value.logo.startsWith('/uploads')) {
      // 尝试添加公共路径
      const newSrc = `/public${form.value.logo}`
      console.log('尝试路径1:', newSrc)
      img.src = newSrc
    } else if (form.value.logo && form.value.logo.includes('/api/')) {
      // 去掉/api前缀
      const newSrc = form.value.logo.replace('/api/', '/')
      console.log('尝试路径2:', newSrc)
      img.src = newSrc
    }
  }, 300)
}

// Logo上传前验证
const beforeLogoUpload = (file) => {
  console.log('准备上传Logo文件:', file.name, file.type, file.size)
  
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  
  // 检查文件大小
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('上传的Logo不能超过2MB!')
    return false
  }
  
  return true
}

// Logo上传成功
const handleLogoSuccess = (res) => {
  console.log('Logo上传成功，原始响应:', res)
  try {
    // 尝试解析响应数据
    let data = res
    if (typeof res === 'string') {
      data = JSON.parse(res)
    }
    
    console.log('解析后的响应数据:', data)
    
    if (data && data.data && data.data.url) {
      form.value.logo = data.data.url
      ElMessage.success('Logo上传成功')
    } else {
      console.error('Logo上传成功但返回数据格式不正确:', data)
      ElMessage.error('Logo上传成功但返回数据格式不正确')
    }
  } catch (error) {
    console.error('处理Logo上传响应时出错:', error)
    ElMessage.error('处理Logo上传响应时出错: ' + error.message)
  }
}

// Logo上传失败
const handleLogoError = (err) => {
  console.error('Logo上传失败:', err)
  let errorMsg = '上传失败'
  
  try {
    if (typeof err.message === 'string') {
      errorMsg = err.message
    } else if (err.response && err.response.data) {
      const data = err.response.data
      errorMsg = data.message || '上传失败'
    }
  } catch (e) {
    console.error('解析上传错误时出错:', e)
  }
  
  ElMessage.error(`Logo${errorMsg}`)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    await updateConfig(form.value)
    ElMessage.success('保存成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('保存失败')
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchConfig()
})
</script>

<style scoped>
.settings-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-upload {
  text-align: center;
}

.logo-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.logo {
  width: 200px;
  height: 60px;
  object-fit: contain;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
}

:deep(.el-upload) {
  width: 200px;
  height: 60px;
  line-height: 60px;
}
</style> 